package com.xb.loan.util.file;

import org.apache.commons.io.FileUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import javax.imageio.stream.FileImageInputStream;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

public class FileUtil {
	private static Log log = LogFactory.getLog(FileUtil.class);

	public static void moveFileToDir(File srcFile, String destPath)
			throws IOException {
		File destDir = new File(destPath);
		FileUtils.copyFileToDirectory(srcFile, destDir);
		srcFile.delete();
	}

	public static void moveFileToDir(String srcFilePath, String destPath)
			throws IOException {
		File srcFile = new File(srcFilePath);
		File destDir = new File(destPath);
		FileUtils.copyFileToDirectory(srcFile, destDir);
		srcFile.delete();
	}

	/**
	 * 命名结果文件
	 * 
	 * @param payFile
	 * @return
	 */
	public static String nameResultFile(String payFile) {
		// 去掉后缀
		payFile = payFile.substring(0, payFile.lastIndexOf("."));

		String resultFile = "RESULT_" + payFile + ".zip";
		return resultFile;
	}
	
	/**
     * 命名结果文件
     * 
     * @param payFile
     * @return
     */
    public static String nameResultDir(String payFile) {
        // 去掉后缀
        payFile = payFile.substring(0, payFile.lastIndexOf("."));

        String resultFile = "RESULT_" + payFile;
        return resultFile;
    }
    
    /**
     * 获取zip文件中，后缀为suffix的第一个文件，并重命名为targetFileName
     * @param zipFile
     * @param targetDir
     * @param suffix
     * 2015-9-9 by lottery
     */
    public static void unzipFirstFile(String zipFile, String targetDir, String suffix, String targetFileName){
        log.info("----unzipFie----："+zipFile);
        ZipInputStream Zin = null;
        BufferedInputStream Bin = null;
        try {
            Zin = new ZipInputStream(new FileInputStream(zipFile));
            Bin = new BufferedInputStream(Zin);
            File Fout = null;
            ZipEntry entry;
            while ((entry = Zin.getNextEntry()) != null && !entry.isDirectory()) {
                String fname = entry.getName();
                log.info("----unzipFies ----："+fname);
                if(fname.contains("ALIPAY__RESULT") || !fname.matches(".*"+suffix)){
                    continue;
                }
                Fout = new File(targetDir, targetFileName);
                if (!Fout.exists()) {
                    (new File(Fout.getParent())).mkdirs();
                }
                FileOutputStream out = new FileOutputStream(Fout);
                BufferedOutputStream Bout = new BufferedOutputStream(out);
                int b;
                while ((b = Bin.read()) != -1) {
                    Bout.write(b);
                }
                Bout.close();
                out.close();
                break;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (Zin != null) {
                    Bin.close();
                    Zin.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    

	/**
	 * 解压文件(只对支付宝结果文件)
	 * @param zipFile
	 * @param targetDir
	 */
	public static void unzipFile(String zipFile, String targetDir) {
		log.info("----unzipFie----："+zipFile);
		ZipInputStream Zin = null;
		BufferedInputStream Bin = null;
		try {
			Zin = new ZipInputStream(new FileInputStream(zipFile));
			Bin = new BufferedInputStream(Zin);
			File Fout = null;
			ZipEntry entry;
			while ((entry = Zin.getNextEntry()) != null && !entry.isDirectory()) {
				String fname = entry.getName();
				log.info("----unzipFies ----："+fname);
				if(fname.contains("ALIPAY__RESULT") || fname.matches(".*\\.xls")){
					continue;
				}
				Fout = new File(targetDir, fname);
				if (!Fout.exists()) {
					(new File(Fout.getParent())).mkdirs();
				}
				FileOutputStream out = new FileOutputStream(Fout);
				BufferedOutputStream Bout = new BufferedOutputStream(out);
				int b;
				while ((b = Bin.read()) != -1) {
					Bout.write(b);
				}
				Bout.close();
				out.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (Zin != null) {
					Bin.close();
					Zin.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	

	/**
	 * 按行读取文件
	 * @param file
	 * @param charSet
	 * @return
	 * 2015-9-15 by lottery
	 */
    public static List<String> readFileByLine(File file, String charSet) {
        List<String> result = null;
        BufferedReader reader = null;
        try {
            if (!file.exists() || !file.isFile()) {
                return null;
            }
            reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), charSet));
            result = new ArrayList<String>();
            String line = null;
            while ((line = reader.readLine()) != null) {
                result.add(line);
            }
            reader.close();
        } catch (Exception e) {
            result = null;
            log.warn("readFileByLine throws a exception", e);
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                    reader = null;
                } catch (Exception e) {
                }
            }
        }
        return result;
    }

	public static byte[] image2byte(String path){
		byte[] data = null;
		FileImageInputStream input = null;
		try {
			input = new FileImageInputStream(new File(path));
			ByteArrayOutputStream output = new ByteArrayOutputStream();
			byte[] buf = new byte[1024];
			int numBytesRead = 0;
			while ((numBytesRead = input.read(buf)) != -1) {
				output.write(buf, 0, numBytesRead);
			}
			data = output.toByteArray();
			output.close();
			input.close();
		}
		catch (FileNotFoundException ex1) {
			ex1.printStackTrace();
		}
		catch (IOException ex1) {
			ex1.printStackTrace();
		}
		return data;
	}

}